package com.zgr.struts.dao.daoimpl;

import com.zgr.struts.dao.IUserDao;
import com.zgr.struts.entity.User;
import com.zgr.struts.utils.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import java.util.List;

public class UserDaoImpl implements IUserDao {

    @Override
    public boolean login(User user) {

        System.out.println("username:" + user.getUsername());
        System.out.println("password:" + user.getPwd());
        //获取Hibernate的session
        Session session = HibernateUtil.getSession();
        //开启事务
        Transaction tx = session.beginTransaction();
        //编写hql语句   User:为User实体类，username,pwd为User类里面的成员变量
        String hql = "FROM User user WHERE user.username=:username AND user.pwd=:password";
        Query query = session.createQuery(hql);
        query.setParameter("username", user.getUsername());
        query.setParameter("password", user.getPwd());
        List<User> list = query.list();
        for (User u: list) {
            System.out.println(u);
        }
        //关闭事务
        tx.commit();
        if(list.size() > 0){
            return true;
        }
        return false;
    }

    @Override
    public void register(User user) {
        //查看用户输入的数据
        System.out.println(user);
        //获取Hibernate的session
        Session session = HibernateUtil.getSession();
        //开启事务
        Transaction tx = session.beginTransaction();
        //编写hql语句   User:为User实体类，username,pwd为User类里面的成员变量
        session.save(user); //执行添加操作
        tx.commit();
    }
}
